package com.guqj.nio.netty.pstack.util;

import io.netty.buffer.ByteBuf;

import java.io.IOException;

import org.jboss.marshalling.Marshaller;

import com.guqj.nio.netty.serialization.marshalling.MarshallingCodeCFactory;


public class NettyMarshallingEncoder {

	private final static byte[] LENGTH_PLACEHOLDER = new byte[4];
	private Marshaller marshaller;

	public NettyMarshallingEncoder() throws IOException {
		marshaller = MarshallingCodeCFactory.buildMarshalling();
	}

	protected void encode(Object msg, ByteBuf out) throws IOException {
		try {
			int lengthPos = out.writerIndex();
			out.writeBytes(LENGTH_PLACEHOLDER);
			ChannelBufferByteOutput output = new ChannelBufferByteOutput(out);
			marshaller.start(output);
			marshaller.writeObject(msg);
			marshaller.finish();
			out.setInt(lengthPos, out.writerIndex() - lengthPos - 4);
		} finally {
			marshaller.close();
		}
	}
}
